/**
 * 
 */
package com.java.test.filter;

import com.alibaba.fastjson.JSONObject;
import com.java.test.system.dto.LoginAccountInfo;
import com.java.test.util.JsonUtil;
import com.java.test.util.RedisUtil;
import com.java.test.util.TokenUtil;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.PrintWriter;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author token 拦截验证
 *
 */
@Component
public class TokenInterceptor implements HandlerInterceptor {

	@Autowired
	RedisUtil redisUtil;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
//		response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));// 支持跨域请求
//		response.setHeader("Access-Control-Allow-Methods", "*");
//		response.setHeader("Access-Control-Allow-Credentials", "true");// 是否支持cookie跨域
//		response.setHeader("Access-Control-Allow-Headers",
//				"Authorization,Origin, X-Requested-With, Content-Type, Accept,Access-Token");

		if (request.getMethod().equals("OPTIONS")) {
			response.setStatus(HttpServletResponse.SC_OK);
			return true;
		}
		response.setCharacterEncoding("utf-8");
		String token = request.getHeader("token");
		if (token == null || "".equals(token)) {
			token = request.getAttribute("token") != null ? request.getAttribute("token").toString() : null;
		}
		boolean check = false;
		if (token != null) {
		//	List<Object> obj = redisUtil.hsetvalues("ONLINE_USER");
			boolean isexit = false;
//			for (Object b : obj) {
//				List<LoginAccountInfo> ilist = JsonUtil.jsonArray2List(b.toString(), LoginAccountInfo.class);
//				for (LoginAccountInfo c : ilist) {
//					if (c == null)
//						continue;
//					String rtoken = c.getTokenVerify();
//					if (rtoken == null || rtoken.length() <= 0 || "".equals(rtoken)) {
//						continue;
//					}
//					if (rtoken.equals(token)) {
//						isexit = true;
//						check = true;
//					}
//				}
//			}

			String sessionId = request.getSession().getId();

			String loginuser = TokenUtil.getLoginUser(token);

			Object obj = redisUtil.hgetvalues("ONLINE_USER_SESSION", loginuser);

			if (obj != null && !"".equals(obj)) {
				if (sessionId.equals(obj.toString())) {
					isexit = true;
					check = true;
				}
			}

			boolean result = TokenUtil.verify(token, request);
			if (result && isexit) {
//				 TokenUtil.getBodyStringByReader(request.getReader()); */
				return true;
			}
		} else {
			System.out.println("TOKEN IS NULL");
		}
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json; charset=utf-8");
		try {
			JSONObject json = new JSONObject();
			if (check) {
				json.put("msg", "token verify fail");
				json.put("code", "50000");
			} else {
				json.put("msg", "token verify fail");
				json.put("code", "50001");
			}
			// response.getWriter().append(json.toJSONString());

			{

				// 重置response
				// response.reset();
				// 设置编码格式
				response.setCharacterEncoding("UTF-8");
				response.setContentType("application/json;charset=UTF-8");

				PrintWriter pw = response.getWriter();

				pw.write(json.toJSONString());

				pw.flush();
				pw.close();

			}
		} catch (Exception e) {
			e.printStackTrace();
			response.sendError(500);
			return false;
		}
		return false;
	}

}
